package com.base.hong.utils

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.pm.PackageManager
import android.text.Html
import android.text.Spanned
import android.text.TextUtils
import android.util.Log
import com.base.hong.app.MyApp
import com.google.gson.Gson
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.*


/**
 * @ClassName HUtils
 * @Author Hong
 * @Date 2022/3/1 11:03
 * @Version 1.0
 */
object HUtils {


    /**
     * 转json串提交
     *
     * @param paramsMap
     * @return
     */
    fun toJson(paramsMap: Map<String, String>): RequestBody {
        val body: RequestBody
        val gson = Gson()
        val strEntity = gson.toJson(paramsMap)
        body = strEntity.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
        return body
    }

    fun <T> toJson(entity: T): RequestBody {
        val body: RequestBody
        val gson = Gson()
        val strEntity = gson.toJson(entity)
        body = strEntity.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
        return body
    }

    /** md5加密 */
    fun md5(content: String): String {
        val hash = MessageDigest.getInstance("MD5").digest(content.toByteArray())
        val hex = StringBuilder(hash.size * 2)
        for (b in hash) {
            var str = Integer.toHexString(b.toInt())
            if (b < 0x10) {
                str = "0$str"
            }
            hex.append(str.substring(str.length - 2))
        }
        return hex.toString()
    }

    /**
     * 判读APK 是否安装
     */
    fun isApkInstalled(context: Context, packageName: String?): Boolean {
        return if (TextUtils.isEmpty(packageName)) {
            false
        } else try {
            context.packageManager.getApplicationInfo(
                packageName!!, PackageManager.MATCH_UNINSTALLED_PACKAGES
            )
            true
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            false
        }
    }

    /**
     * 复制文本
     */
    fun String?.copyString(): Boolean {
        if (isNullOrBlank()) {
            return false
        }
        // 获取系统剪贴板
        val clipboard =
            MyApp.getContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）,其他的还有
        val clipData = ClipData.newPlainText(null, this)
        // 把数据集设置（复制）到剪贴板
        clipboard.setPrimaryClip(clipData)
        return true
    }

    fun getHtmlFontText(color: String, text: String): String? {
        return "<font color=\"$color\">$text</font>"
    }


    fun getFromHtml(text: String): Spanned {
        var result: Spanned =
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY)
            } else {
                Html.fromHtml(text)
            }
        return result
    }

    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    fun getVersionCode(mContext: Context): Int {
        var versionCode = 0
        try {
            versionCode =
                mContext.packageManager.getPackageInfo(mContext.packageName, 0).versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return versionCode
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    fun getVerName(mContext: Context): String {
        var versionCode = ""
        try {
            versionCode =
                mContext.packageManager.getPackageInfo(mContext.packageName, 0).versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return versionCode
    }

    private val yyyyMMddHHmm = SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.CHINA)
    private val yyyyMMddHHmmss = SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA)
    private val yyyyMMdd = SimpleDateFormat("yyyy/MM/dd", Locale.CHINA)
    private val MMddHHmm = SimpleDateFormat("MM/dd HH:mm", Locale.CHINA)
    private val MMdd = SimpleDateFormat("MM/dd", Locale.CHINA)

    /**
     * 时间戳转换
     *
     * @param date
     * @return
     */
    fun formatDateMMddHHmm(date: Long): String? {
        return MMddHHmm.format(Date(date))
    }

    fun formatDateYyyyMMddHHmm(date: Long): String? {
        return yyyyMMddHHmm.format(Date(date))
    }

    fun formatDateYyyyMMddHHmmss(date: Long): String? {
        return yyyyMMddHHmmss.format(Date(date))
    }

    fun formatDateMMdd(date: Long): String? {
        return MMdd.format(Date(date))
    }

    fun formatDateYyyyMMdd(date: Long): String? {
        return yyyyMMdd.format(Date(date))
    }

    fun ping(urld: String): Boolean {
        var result: String? = null
        try {
            //其中-c 1 是代表次数   -w 1代表的是时间，这里要注意下时间是秒
            val p = Runtime.getRuntime().exec("ping -c 1 -w 1 $urld") //
            // PING的状态
            val status = p.waitFor()
            if (status == 0) {
                result = "successful~"
                return true
            } else {
                result = "failed~ cannot reach the IP address"
                return false
            }
        } catch (e: IOException) {
            return false
            result = "failed~ IOException"
        } catch (e: InterruptedException) {
            return false
            result = "failed~ InterruptedException"
        } finally {
            Log.i("TTT", "result = $result")
        }
        return true
    }
}